// subpage/pages/orderdetail/orderdetail.js
const app = getApp();
import service from '../../../utils/request'
import { _allowStateChangesInsideComputed } from 'mobx-miniprogram';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showZhan: false,
   
  zhan:[],
    ballInfo: {ballType:'all',ballSize:400,waveColor:'#ffffff',ballPadding:'0'},
    loadPercent: 40,
    baseUrl: app.data.url,
    free:false,
    order:{},
    oid:'',
    active:1,
    isStop:false,
    gun:{},
    // soketUrl: 'wss://127.0.0.1:8443/v1',
    soketUrl:"wss://wxsocket.ztkuaichong.com:3027?token="+wx.getStorageSync('token'),
    isReq: false,
    isPull: false,
    carnumber:'',
    interval: '',
    isHide: false,
    setTime: 30000,
    onSocketLine: false,
    showAmout: false,
    go: '',//来源
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log('ssss',options)
       //soket初始化
    this.setData({
      oid: options.oid,
      isHide: false
    })
    if(options.go){
      this.setData({
        go: options.go
      })
    }
   
    
    // this.inSoket()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  showDetail(){
    this.setData({
      showAmout: !this.data.showAmout
    })
  },
  phoneCall(){
    wx.makePhoneCall({
      phoneNumber: '4001071368' 
    })
  },
  palteTab(){
    let that = this
    let result = service('GET','/parking/exemption/'+this.data.oid,{}).then(res => {
      console.log('停车减免',res)
      // return
      if(res.data.code ==0){
        wx.showToast({
          title: '减免成功',
          icon:'none'
        })
        that.setData({
          "order.plateState": 3
        })
      }else{
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
      }
    })
  },
  goback(){
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    this.setData({
      isHide: false
    })
   that.onSoket()
    this.orderSelect()
    this.getSiteOut()
  },

  //占位
  getSiteOut(){
    service("GET", "/order/info/"+this.data.oid).then(res => {
      console.log('超时占位',res)
      if(res.data.code == 0){
        let data = res.data.list
        // let data = [{
        //   "beginTime": "2022-03-01 06:01:34",
        //   "costBeginTime": "2022-03-01 06:01:34",
        //   "desc": "收费规则，收费规则收费规则收费规则收费规则收费规则",
        //   "endTime": "2022-03-01 06:01:34",
        //   "freeTime": 0,
        //   "receivedPrice": 12,
        //   "rule": {},
        //   "time": 378,
        //   "total": 0
        // },{
        //   "beginTime": "2022-03-01 06:01:34",
        //   "costBeginTime": "2022-03-01 06:01:34",
        //   "desc": "收费规则，收费规则收费规则收费规则收费规则收费规则",
        //   "endTime": "2022-03-01 06:01:34",
        //   "freeTime": 0,
        //   "receivedPrice": 34,
        //   "rule": {},
        //   "time": 1254,
        //   "total": 0
        // }]
        data.map(item => {
          item.time = (item.time/60).toFixed(0)
          return item
        })
        this.setData({
          zhan: data
        })
      }
    })
  },
  onSoket(state){
    let that = this
    console.log('onSoket');
    wx.connectSocket({
      url: that.data.soketUrl,
      success: ()=> {
        console.log('connectSocket')
      }
    })
    
    wx.onSocketOpen((res) => {
      console.log('检测到soket ', res);
      // that.setData({
      //   onSocketLine: true
      // })
      this.getRefresh()
      //清除定时器
      // clearInterval(that.data.interval)
       //接受数据
    })
    wx.onSocketClose(function (res) {
      console.log('onSocketClose检测到socket链接关闭！，发起定时器detail')
      that.setData({
        onSocketLine: false
      })
      // if(!that.data.interval && that.data.isHide == false){
      //   console.log('检测到soket 已关闭！，发起定时器detail')
      //   that.setIntervel(state)
      // }else{
      // }
    })

   
  },
  cancelZhan(){
    console.log('占位')
    this.setData({
      showZhan: !this.data.showZhan
    })
  },
  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this
    this.setData({
      isHide: true
    })
    wx.closeSocket({
      complete:() => {
        console.log('detail测试hide关闭soket，删除定时器')
        clearInterval(that.data.interval)
      }
     })
  },
  getRefresh(){
    let that = this
     //接受数据
     console.log('拉取soket数据')
     wx.onSocketMessage((data) => {
      that.setData({
        onSocketLine: true
      })
      // clearInterval(this.data.interval)
      let da = JSON.parse(data.data)
      let result = da.detail
      let state = da.type ===3 ? 2 : da.type === 8 ? 3: da.type == 5 ? 4: da.type
      let settlement = da.type == 4 ? false: true
      console.log('soket成功返回11',da, state);
      if(result){
        // result.surplusTime = result.surplusTime ? parseInt(result.surplusTime/60) :0
        let surplusTime = result.surplusTime ? parseInt(result.surplusTime/60) :0
        result.surHours = Math.floor(surplusTime/60) < 10 ? '0'+Math.floor(surplusTime/60) : ''+Math.floor(surplusTime/60)
        let surMin = surplusTime - (Math.floor(surplusTime/60)*60)
        result.surMin = surMin < 10 ? '0'+surMin : ''+surMin
        let chargeTime=  result.chargeTime ? result.chargeTime : that.data.order.chargeTime
        let shi = parseInt(chargeTime/3600) 
        let hour = shi >=10 ? shi : '0'+shi
        let min  =  Math.ceil((chargeTime - (parseInt(chargeTime/3600))*3600)/60)
        min = min >=10 ? min : '0'+min
        console.log('时分', shi, hour , min, result.chargeTime ,result)
        let total = (result.powerPrice + result.servicePrice).toFixed(2)
        
        let totalAmout = result.amount ? result.amount : 0
        that.setData({
          ['order.soc']: result.soc,
          ['order.totalAmout']: totalAmout,
          ['order.shi']: hour,
          ['order.chargeTime'] :chargeTime,
          ['order.fen']: min,
          ['order.total']:total,
          ['order.powerPrice']: result.powerPrice,
          ['order.servicePrice']: result.servicePrice,
          ['order.surHours']: result.surHours,
          ['order.surMin']: result.surMin,
          ['order.voltage']: result.voltage,
          ['order.current']: result.current,
          ['order.electricity']: result.electricity,
          ['order.electricity']: result.electricity,
          ['order.power']: result.power,
          ['order.state']: state,
          ['order.settlement']: settlement,
          
        })
      }else {
        if(da.type  ==4 || da.type == 5){
          that.orderSelect()
        }
        // if(da.type == 6 || da.type == 7){
        //   wx.navigateTo({
        //     url: '/subpage/pages/plan/plan',
        //   })
        //   return
        // }
        that.setData({
          ['order.state']: state,
        })
      }
    })
  },
  //设置定时器访问和重连soket
  setIntervel(state) {
    let that = this
    console.log('进入定时器');
    let time = this.data.setTime
    console.log('state', state)
    that.data.interval = setInterval(function() {
      // wx.connectSocket({
      //   url: that.data.soketUrl
      // })
      that.orderSelect()
       console.log(time,"秒了----------------------------------------------------")
     }, time)
  },
  chargeOrderSoc() {
    let that = this
    service("GET", "/order/charging").then(res => {
      if(res.data.code ===0){
        let order =  res.data.order
        console.log('订单',order)
        if(order.beginTime){
          order.beginTime = order.beginTime.replace(/-/g, "/")
          // console.log('wwww',order.beginTime)
          var data = new Date(order.beginTime)
          order.dayS = data.getDate()
          order.monthS = data.getMonth() + 1
          let ho = data.getHours()
          order.hourS = ho >=10 ?ho : '0'+ho
          let min = data.getMinutes()
          order.minS = min >= 10 ? min : '0'+min
          console.log('data',data,order.month, order.dayS, order.hourS , order.minS)
        }
        let surplusTime = order.surplusTime ? parseInt(order.surplusTime/60) :0
        order.surHours = Math.floor(surplusTime/60) < 10 ? '0'+Math.floor(surplusTime/60) : ''+Math.floor(surplusTime/60)
        let surMin = surplusTime - (Math.floor(surplusTime/60)*60)
        order.surMin = surMin < 10 ? '0'+surMin : ''+surMin
        if(order.endTime){
          order.endTime = order.endTime.replace(/-/g, "/")
          var end = new Date(order.endTime)
          order.dayEnd = end.getDate()
          order.monthEnd = end.getMonth() + 1
          var he =  end.getHours()
          order.hourEnd = he >=10 ?he : '0'+he
          let hm = end.getMinutes()
          order.minEnd = hm >= 10 ? hm : '0'+hm
          console.log(order.endTime, order.dayEnd)
        }
        let shi = order.chargeTime ? parseInt(order.chargeTime/3600) :0
        order.shi = shi >=10 ? shi : '0'+shi
        let fen  = order.chargeTime ? Math.ceil((order.chargeTime - (parseInt(order.chargeTime/3600))*3600)/60)  : 0
        order.fen = fen >=10 ? fen : '0'+fen
        order.totalAmout = order.amount
        let t = new Date(order.beginTime).getTime() + 24 * 60 * 60 * 1000
        let d = new Date().getTime()
        let free = false
        if(t > d){
          free = true
        }
        console.log('订单',data)
        that.setData({
          order: res.data.detail,
          free: free
        })
        if(that.data.isPull){
          console.log('已更新订单')
          wx.showToast({
            title: 'title',
            duration:1000
          })
          wx.stopPullDownRefresh()
          
        }
        // if(order.state == 6 || order.state == 7|| order.state == 5){
        //   wx.navigateTo({
        //     url: '/subpage/pages/plan/plan',
        //   })
        //   return
        // }
        that.getGun(order.gunSn)
        if(order.state !== 4){
          wx.onSocketClose(function (res) {
            if(!that.data.interval){
              console.log('检测到soket已关闭！，重连socket')
              that.onSoket(order.state)
            }
          })
          
        }
      }else{
        this.orderDetail()
      }
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // this.storeBindings.destroyStoreBindings()
    let that = this
    this.setData({
      isHide: true
    })
    wx.closeSocket({
      complete:() => {
        console.log('detail测试onUnload关闭soket，删除定时器')
        clearInterval(that.data.interval)
      }
     })
     if(this.data.go == 'charge'){
       wx.navigateBack({
         delta: 2,
       })
     }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //下拉刷新
    this.setData({
      isPull:true
    })
     this.orderSelect()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //详情
  orderSelect() {
    let that = this
    service("GET", "/order/charging").then(res => {
      if(res.data.code ===0){
        let order =  res.data.order
        console.log('订单',order)
        if(order.beginTime){
          order.beginTime = order.beginTime.replace(/-/g, "/")
          // console.log('wwww',order.beginTime)
          var data = new Date(order.beginTime)
          order.dayS = data.getDate()
          order.monthS = data.getMonth() + 1
          let ho = data.getHours()
          order.hourS = ho >=10 ?ho : '0'+ho
          let min = data.getMinutes()
          order.minS = min >= 10 ? min : '0'+min
          console.log('data',data,order.month, order.dayS, order.hourS , order.minS)
        }
        let surplusTime = order.surplusTime ? parseInt(order.surplusTime/60) :0
        order.surHours = Math.floor(surplusTime/60) < 10 ? '0'+Math.floor(surplusTime/60) : ''+Math.floor(surplusTime/60)
        let surMin = surplusTime - (Math.floor(surplusTime/60)*60)
        order.surMin = surMin < 10 ? '0'+surMin : ''+surMin
        if(order.endTime){
          order.endTime = order.endTime.replace(/-/g, "/")
          var end = new Date(order.endTime)
          order.dayEnd = end.getDate()
          order.monthEnd = end.getMonth() + 1
          var he =  end.getHours()
          order.hourEnd = he >=10 ?he : '0'+he
          let hm = end.getMinutes()
          order.minEnd = hm >= 10 ? hm : '0'+hm
          console.log(order.endTime, order.dayEnd)
        }
        let shi = order.chargeTime ? parseInt(order.chargeTime/3600) :0
        order.shi = shi >=10 ? shi : '0'+shi
        let fen  = order.chargeTime ? Math.ceil((order.chargeTime - (parseInt(order.chargeTime/3600))*3600)/60)  : 0
        order.fen = fen >=10 ? fen : '0'+fen
        order.totalAmout = order.amount
        let t = new Date(order.beginTime).getTime() + 24 * 60 * 60 * 1000
        let d = new Date().getTime()
        let free = false
        if(t > d){
          free = true
        }
        console.log('订单',data)
        this.setData({
          order: order,
          free: free
        })
        if(this.data.isPull){
          console.log('已更新订单')
          wx.showToast({
            title: 'title',
            duration:1000
          })
          wx.stopPullDownRefresh()
          
        }
        // if(order.state == 6 || order.state == 7|| order.state == 5){
        //   wx.navigateTo({
        //     url: '/subpage/pages/plan/plan',
        //   })
        //   return
        // }
        that.getGun(order.gunSn)
        if(order.state !== 4){
          if(order.state == 0 || order.state == 1 || order.state == 3){
            if(that.data.setTime == 15000){
              clearInterval(that.data.interval)
              that.setData({
                interval: ''
              })
            }
            that.setData({
              setTime: 6000
            })
            console.log('设置6000', that.data.isHide, that.data.interval)
          }else{
            if(that.data.setTime == 6000){
              clearInterval(that.data.interval)
              that.setData({
                interval: ''
              })
            }
            that.setData({
              setTime: 15000
            })
            console.log('设置15000', that.data.isHide, that.data.interval)
          }
          wx.onSocketClose(function() {
            that.setData({
              onSocketLine: false
            })
          console.log('onSocketClose检测到socket链接关闭！，发起定时器detail');
        })
        console.log('经过onSocketClose检查');
        if(!that.data.interval && that.data.isHide == false && !that.data.onSocketLine && (order.state != 6 && order.state != 7 && order.state != 5)){
          console.log('检测到soket 已关闭！，发起定时器detail')
          that.setIntervel()
        }else{
          console.log('检测到soket 已关闭！，卸载隐藏页面，不发起定时器detail',that.data.interval ,that.data.onSocketLine)
        }
          // that.onSoket(1)
        }else{
          clearInterval(that.data.interval)
        }
      }else{
        this.orderDetail()
      }
    })
  },

  orderDetail() {
    let that = this
    service("GET", "/order/detail/"+this.data.oid).then(res => {
      if(res.data.code ===0){
        let order =  res.data.detail
        console.log('订单',order)
        if(order.beginTime){
          order.beginTime = order.beginTime.replace(/-/g, "/")
          // console.log('wwww',order.beginTime)
          var data = new Date(order.beginTime)
          order.dayS = data.getDate()
          order.monthS = data.getMonth() + 1
          let ho = data.getHours()
          order.hourS = ho >=10 ?ho : '0'+ho
          let min = data.getMinutes()
          order.minS = min >= 10 ? min : '0'+min
          console.log('data',data,order.month, order.dayS, order.hourS , order.minS)
        }
        let surplusTime = order.surplusTime ? parseInt(order.surplusTime/60) :0
        order.surHours = Math.floor(surplusTime/60) < 10 ? '0'+Math.floor(surplusTime/60) : ''+Math.floor(surplusTime/60)
        let surMin = surplusTime - (Math.floor(surplusTime/60)*60)
        order.surMin = surMin < 10 ? '0'+surMin : ''+surMin
        if(order.endTime){
          order.endTime = order.endTime.replace(/-/g, "/")
          var end = new Date(order.endTime)
          order.dayEnd = end.getDate()
          order.monthEnd = end.getMonth() + 1
          var he =  end.getHours()
          order.hourEnd = he >=10 ?he : '0'+he
          let hm = end.getMinutes()
          order.minEnd = hm >= 10 ? hm : '0'+hm
          console.log(order.endTime, order.dayEnd)
        }
        let shi = order.chargeTime ? parseInt(order.chargeTime/3600) :0
        order.shi = shi >=10 ? shi : '0'+shi
        let fen  = order.chargeTime ? Math.ceil((order.chargeTime - (parseInt(order.chargeTime/3600))*3600)/60)  : 0
        order.fen = fen >=10 ? fen : '0'+fen
        order.totalAmout = order.amount
        console.log('订单',data)
        this.setData({
          order: res.data.detail
        })
        if(this.data.isPull){
          console.log('已更新订单')
          wx.showToast({
            title: 'title',
            duration:1000
          })
          wx.stopPullDownRefresh()
          
        }
        // if(order.state == 6 || order.state == 7|| order.state == 5){
        //   wx.navigateTo({
        //     url: '/subpage/pages/plan/plan',
        //   })
        //   return
        // }
        this.getGun(order.gunSn)
        if(order.state !== 4){
          if(order.state == 0 || order.state == 1 || order.state == 3){
            if(that.data.setTime == 15000){
              clearInterval(that.data.interval)
              that.setData({
                interval: ''
              })
            }
            that.setData({
              setTime: 6000
            })
            console.log('设置6000', that.data.isHide, that.data.interval)
          }else{
            if(that.data.setTime == 6000){
              clearInterval(that.data.interval)
              that.setData({
                interval: ''
              })
            }
            that.setData({
              setTime: 15000
            })
            console.log('设置15000', that.data.isHide, that.data.interval)
          }
          wx.onSocketClose(function() {
            that.setData({
              onSocketLine: false
            })
          console.log('websocket onSocketError');
        })
        if(!that.data.interval && that.data.isHide == false && !that.data.onSocketLine && (order.state != 6 && order.state != 7 && order.state != 5)){
          console.log('检测到soket 已关闭！，发起定时器detail')
          that.setIntervel()
        }else{
          console.log('检测到soket 已关闭！，卸载隐藏页面，不发起定时器detail',that.data.interval ,that.data.isHide)
        }
          // that.onSoket(1)
        }else{
          clearInterval(that.data.interval)
        }
      }
    })
  },

  animation() {
    let animation1 = wx.createAnimation({
      transformOrigin: "0 50% 50%",
      duration: 1000,
      timingFunction: "ease",
      delay: 0
     });
  },
  //复制订单号
  copyOrder(){
    wx.setClipboardData({
      data:this.data.order.oid,
      success:function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      }
    })
  },
  //充电枪详情
  getGun(gun){
    let that = this
    service('GET', '/iot/gun/info/sn/'+gun).then(res => {
      that.setData({
        gun:res.data.info
      })
    })
  },
  stopCharge() {
    let that = this
    this.setData({
      isStop: true
    })
    service("GET", "/order/stop").then(res => {
      if(res.data.code ===0){
        // this.updateShowPercent(false)
        // wx.switchTab({
        //   url: '/pages/scen/scen',
        // })
        that.setData({
          ['order.state']: 3,
        })
        wx.showToast({
          title:'正在停止设备，请稍等。长时间无响应，请下拉刷新',
          icon: 'none',
          duration: 5000
        })
      }else{
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  goSite(){
    wx.navigateTo({
      url: '/subpage/pages/sitedetail/sitedetail?id='+this.data.order.siteId,
    })
  },
  //支付
  orderPay (e) {
    let amout = e.target.dataset.total
    if(!!amout == false){
      wx.showToast({
        title: '支付金额有误',
        icon: "none"
      })
      return
    }
    wx.request({
      url: baseUrl+'url',
    })
  },
      //修改车牌号
      editPlate() {
        let that  = this
        wx.navigateTo({
              url: '/subpage/pages/carbeand/carbeand?carnumber='+this.data.order.plate+'&oid='+this.data.order.oid,
              events:{
                onCar(res){
                  console.log(res);
                  if(!res || res == 'undefine'){
                    that.setData({
                      ['order.plate']:'',
                    })
                  }else{
                    that.setData({
                      ['order.plate']:res,
                    })
                  }
                  
                }
              }
            })
      },
})